<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/6/21
 * Time: 9:38
 */

namespace traits\controller;

use app\admin\Imp\ImpDecorate;
use \ReflectionClass;
use think\Exception;
trait Decorate
{
    private $decorate       =   [];
    private $pre_decorate   =   'Decorate';
    private $instance       =   '';
    private $objectName     =   '';
    protected function    _checkDecorate()
    {
        $commonDecorate = config($this->pre_decorate . '.CommonDecorate');
        $moduleDecorate = empty(config($this->pre_decorate . '.' . $this->action)) ? [] : config($this->pre_decorate . '.' . $this->action);
        $commonDecorate = array_merge($commonDecorate, $moduleDecorate);
        array_map(function ($element) {
            $name = basename($element);
            $this->objectName       =   $element;
            $this->instance         =   $this->_Instance();
            $this->_addDecorate($this->instance, $name);
        }, $commonDecorate);
    }

    /**
     * @author                      |-开发者lqc
     * @modifier                    |-修改者lqc
     * @time                        |-开发时间2017年6月21日10:48:59
     * @modify_time                 |-修改时间2017年6月21日10:49:09
     * @param ImpDecorate $decorate |-添加我们的装饰器
     * @param $name                 |-给我们的装饰器起的名字
     * @use                         |-添加装饰器
     */
    private function _addDecorate(ImpDecorate $decorate, $name)
    {
        $this->decorate[$name] = $decorate;
    }

    /**
     *前置操作
     */
    protected function _beforeDecorate()
    {
        foreach ($this->decorate as $key => $decorate) {
            if(!method_exists($decorate,'beforeDecorate')){continue;}
            $decorate->beforeDecorate();
        }
        if(!empty($this->beforeHandle)){self::_beforeAction();}
    }
    /**
     * 获得对象实例
     */
    private function _Instance(){
       $reflection              =   new ReflectionClass($this->objectName);
       $instance                =   $reflection->newInstanceArgs();
       return $instance;
    }

    /**
     * 后置操作
     */
    protected function _endDecorate()
    {
        if(!empty($this->endHandle)){self::_endAction();}
        $decorates               =   array_reverse($this->decorate);
        foreach ($decorates as $key => $decorate) {
            if(!method_exists($decorate,'endDecorate')){continue;}
            $decorate->endDecorate();
        }
    }

    /**
     * @return bool 前置处理方法
     */
    private function _beforeAction(){
        foreach($this->beforeHandle  as $key=>$value){
            $this->$key($value);
            $this->beforeHandle[$key]=  $value;
        }
    }

    /**
     * @return bool 后置处理方法
     */
    private function _endAction(){
        foreach($this->endHandle  as $key=>$value){
            $this->$key($value);
            $this->endHandle[$key]  =   $value;
        }
    }
}